package com.desaysv.mvi.model

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.desaysv.mvi.intent.IIntent
import com.desaysv.mvi.state.IState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

/**
 * @author linzi
 * @date 2023-3-31
 */
abstract class BaseViewModel<T : IIntent,E : IState>(default:E) : ViewModel() {
    val currentIntent = Channel<T>(Channel.UNLIMITED)
    val currentState = MutableStateFlow<E>(default)

    /**
     * intent的消费者
     */
    abstract fun intentConsumer(intent:T)

    init {
        handleIntent()
    }

    /**
     * 初始化消费者
     */
    private fun handleIntent(){
        viewModelScope.launch {
            currentIntent.consumeAsFlow().collect{
                intentConsumer(it)
            }
        }
    }

}